import 'package:baby_health_tracker/widgets/add_custom_record_dialog.dart';
import 'package:baby_health_tracker/widgets/add_height_record_dialog.dart';
import 'package:baby_health_tracker/widgets/add_weight_record_dialog.dart';
import 'package:baby_health_tracker/widgets/gradient_app_bar.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../model/baby.dart';
import '../model/health_record.dart';
import '../service/database_service.dart';
import '../ui/ui.dart';
import '../widgets/add_medicine_record_dialog.dart';
import '../widgets/add_vaccine_record_dialog.dart';
import '../widgets/common.dart';
import '../widgets/records_list.dart';
import '../widgets/add_feeding_record_dialog.dart';
import '../widgets/add_diaper_record_dialog.dart';
import '../widgets/add_sleep_record_dialog.dart';
import '../widgets/add_temperature_record_dialog.dart';
import '../widgets/select_record_type_dialog.dart';

class RecordsTab extends StatefulWidget {
  @override
  _RecordsTabState createState() => _RecordsTabState();
}

class _RecordsTabState extends State<RecordsTab> {
  Baby? _selectedBaby;
  RecordType? _selectedType;
  DateTime? _startDate;
  DateTime? _endDate;

  @override
  void initState() {
    super.initState();
    _loadDefaultBaby();
    _startDate = DateTime.now().subtract(const Duration(days: 7));
    _endDate = DateTime.now();
  }

  Future<void> _loadDefaultBaby() async {
    final baby = await DatabaseService().getDefaultBaby();
    setState(() {
      _selectedBaby = baby;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('健康记录'),
        automaticallyImplyLeading: false,
        actions: [
          IconButton(
            icon: Stack(
              children: [
                const Icon(Icons.filter_list),
                if (_selectedType != null ||
                    _startDate !=
                        DateTime.now().subtract(const Duration(days: 7)) ||
                    _endDate != DateTime.now())
                  Positioned(
                    right: 0,
                    top: 0,
                    child: Container(
                      width: 8,
                      height: 8,
                      decoration: BoxDecoration(
                        color: Theme.of(context).colorScheme.primary,
                        shape: BoxShape.circle,
                      ),
                    ),
                  ),
              ],
            ),
            onPressed: _showFilterDialog,
          ),
        ],
      ),
      body: _buildRecordsList(),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () => _showAddRecordDialog(context),
      ),
    );
  }

  void _showFilterDialog() {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('筛选记录'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '记录类型',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                DropdownButton<RecordType?>(
                  isExpanded: true,
                  value: _selectedType,
                  items: [
                    const DropdownMenuItem(value: null, child: Text('全部类型')),
                    ...RecordType.values.map(
                      (type) => DropdownMenuItem(
                        value: type,
                        child: Text(getRecordTypeText(type)),
                      ),
                    ),
                  ],
                  onChanged: (value) => setState(() => _selectedType = value),
                ),
                const SizedBox(height: 16),
                const Text(
                  '时间范围',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                InkWell(
                  onTap: () async {
                    final result = await showDateRangePicker(
                      context: context,
                      firstDate: DateTime(2020),
                      lastDate: DateTime.now(),
                      initialDateRange: DateTimeRange(
                        start: _startDate!,
                        end: _endDate!,
                      ),
                    );
                    if (result != null) {
                      setState(() {
                        _startDate = result.start;
                        _endDate = result.end;
                      });
                    }
                  },
                  child: Padding(
                    padding: const EdgeInsets.symmetric(vertical: 8),
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            '${DateFormat('yyyy-MM-dd').format(_startDate!)} 至\n${DateFormat('yyyy-MM-dd').format(_endDate!)}',
                          ),
                        ),
                        const Icon(Icons.calendar_today),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () {
                  setState(() {
                    _selectedType = null;
                    _startDate = DateTime.now().subtract(
                      const Duration(days: 7),
                    );
                    _endDate = DateTime.now();
                  });
                  Navigator.pop(context);
                },
                child: const Text('重置'),
              ),
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('确定'),
              ),
            ],
          ),
    );
  }

  Widget _buildRecordsList() {
    if (_selectedBaby == null) {
      return const Center(child: Text('请先选择宝宝'));
    }

    return RefreshIndicator(
      onRefresh: () async {
        setState(() {});
      },
      child: FutureBuilder<List<HealthRecord>>(
        future: DatabaseService().getHealthRecords(
          type: _selectedType,
          startDate: _startDate,
          endDate: _endDate,
        ),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return SingleChildScrollView(
              physics: const AlwaysScrollableScrollPhysics(),
              child: SizedBox(
                height: MediaQuery.of(context).size.height - 100,
                child: Center(child: Text('加载失败: ${snapshot.error}')),
              ),
            );
          }

          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }

          if (!snapshot.hasData || snapshot.data!.isEmpty) {
            return SingleChildScrollView(
              physics: const AlwaysScrollableScrollPhysics(),
              child: SizedBox(
                height: MediaQuery.of(context).size.height - 100,
                child: const Center(child: Text('暂无记录')),
              ),
            );
          }

          return ListView.builder(
            physics: const AlwaysScrollableScrollPhysics(),
            itemCount: snapshot.data!.length,
            itemBuilder: (context, index) {
              final record = snapshot.data![index];
              final bool isFirstOfDay =
                  index == 0 ||
                  !_isSameDay(
                    record.timestamp,
                    snapshot.data![index - 1].timestamp,
                  );

              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if (isFirstOfDay)
                    Padding(
                      padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
                      child: Text(
                        _formatDate(record.timestamp),
                        style: Theme.of(context).textTheme.titleSmall?.copyWith(
                          color: Colors.grey[600],
                        ),
                      ),
                    ),
                  Padding(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 8,
                    ),
                    child: Row(
                      children: [
                        Container(
                          width: 40,
                          height: 40,
                          decoration: BoxDecoration(
                            color: getRecordTypeColor(
                              record.type,
                            ).withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Icon(
                            getRecordTypeIcon(record.type).icon,
                            color: getRecordTypeColor(record.type),
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                getRecordTypeText(record.type),
                                style: const TextStyle(
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              Text(
                                _formatRecordData(record),
                                style: TextStyle(color: Colors.grey[600]),
                              ),
                            ],
                          ),
                        ),
                        Text(
                          DateFormat('HH:mm').format(record.timestamp),
                          style: TextStyle(color: Colors.grey[600]),
                        ),
                      ],
                    ),
                  ),
                  if (!isFirstOfDay)
                    Divider(height: 1, indent: 68, color: Colors.grey[200]),
                ],
              );
            },
          );
        },
      ),
    );
  }

  bool _isSameDay(DateTime date1, DateTime date2) {
    return date1.year == date2.year &&
        date1.month == date2.month &&
        date1.day == date2.day;
  }

  String _formatDate(DateTime date) {
    final now = DateTime.now();
    if (_isSameDay(date, now)) {
      return '今天';
    } else if (_isSameDay(date, now.subtract(const Duration(days: 1)))) {
      return '昨天';
    } else {
      return DateFormat('MM月dd日 EEEE', 'zh_CN').format(date);
    }
  }

  String _formatRecordData(HealthRecord record) {
    switch (record.type) {
      case RecordType.feeding:
        return record.formattedAmount;
      case RecordType.diaper:
        return record.data['type'] == 'wet' ? '尿尿' : '便便';
      case RecordType.sleep:
        return '${record.data['duration']}分钟';
      case RecordType.temperature:
        return '${record.data['temperature']}°C';
      case RecordType.medicine:
        return record.data['name'] ?? '';
      default:
        return '';
    }
  }

  void _showAddRecordDialog(BuildContext context) {
    if (_selectedBaby == null) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('请先选择宝宝')));
      return;
    }

    Widget dialog = SelectRecordTypeDialog(
      babyId: _selectedBaby!.id,
      onTypeSelected: (type) {
        Navigator.pop(context);
        showRecordDialogByType(context, type, _selectedBaby!.id);
      },
    );

    showDialog(context: context, builder: (_) => dialog);
  }

  }
